#pragma once

#include <iostream>
#include <fstream>
#include <cassert>
#include <string>
#include <vector>
#include <unordered_map>
#include <algorithm>
#include <mutex>
#include <ctime>
#include "logging.cc"
//#include <boost/filesystem.hpp>
#include <boost/filesystem.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/filesystem/operations.hpp>
#include <boost/algorithm/string.hpp>
#include <jsoncpp/json/json.h>




class DocInfo
{
public:
    uint64_t docId_;
    std::string docTitle_;
    std::string docUrl_;
    std::string docContent_;
};

namespace common
{
    std::string GetTime()
    {
        std::string result;
        time_t rawtime;
        struct tm *ptminfo;
        time(&rawtime);
        ptminfo = localtime(&rawtime);
        result += std::to_string(ptminfo->tm_year + 1900);
        result += " ";
        result += std::to_string(ptminfo->tm_mon + 1);
        result += " ";
        result += std::to_string(ptminfo->tm_mday);
        result += " ";
        result += std::to_string(ptminfo->tm_hour);
        result += ":";
        result += std::to_string(ptminfo->tm_min);
        result += ":";
        result += std::to_string(ptminfo->tm_sec);
        return result;
    }
    bool Read(const std::string& input_path, std::string* content) 
    {
        std::ifstream file(input_path.c_str(), std::ios::binary);
        if (!file.is_open()) 
        {
            return false;
        }
        file.seekg(0, file.end);
        int length = file.tellg();
        file.seekg(0, file.beg);
        // content->resize(length + 1);
        content->resize(length);
        file.read(const_cast<char*>(content->data()), length);
        file.close();
        return true;
    }
    void WriteOut(const DocInfo& doc, std::ofstream& out)
    {
        out << doc.docTitle_ << "\3" << doc.docUrl_ << "\3" << doc.docContent_ << "\n";
    }
    void SplitLineToDoc(DocInfo* doc, const std::string& line, const std::string& split_char)
    {
        std::vector<std::string> output;
        boost::split(output, line, boost::is_any_of(split_char), boost::token_compress_off);
        if(output.size() == 3)
        {
            doc->docTitle_ = output[0];
            doc->docUrl_ = output[1];
            doc->docContent_ = output[2];
        }
    }
    std::string GetSummary(const std::string& key, const std::string& source)
    {
        // 取前50和后100
        size_t pos = source.find(key);
        if(pos == std::string::npos)
        {
            return "";
        }
        size_t left = (pos > 49) ? (pos - 50) : (0);
        // 不能去减 因为 size_t 只有正 超出了限制反而更大
        size_t right = (source.length() > 100 + pos) ? (pos + 100) : (source.length() - 1); 
        return source.substr(left, right - left + 1);
    }   

};

